<?php

class AdminMenuController extends Base {
  use CURD;

  public $tableName = 'admin_menu';
  protected $deleted_at = false;
  protected $isTree = true;
  protected $likeField = 'title'; 
  protected $parentKey = 'parent_id';
  protected $relations = [
    'parent_id' => ['table'=>'admin_menu','as'=>'parent','pri'=>'id','cols'=>['id','title'],'where'=>[],'type'=>'one'],
    'key' => ['table'=>'admin_permissions','as'=>'permissions','pri'=>'parent_id','cols'=>['id','parent_id','name','http_path','slug'],'where'=>[],'type'=>'many'],
  ];
  protected $order = ['order'=>'ASC','id'=>'ASC'];
  
  public function beforeSave($params){
    if(isset($params['key']) && $params['key']){
      $id = $params['id']??0;
      $count = $this->db->count($this->tableName,['id[!]'=>$id,'key'=>$params['key']]);
      if($count){
        error($params['key'].'已存在');
      }
    }
    return $params;
  }  

  public function afterSave($id,$params){
    if(isset($params['key']) && !$params['key']){
      $this->db->update($this->tableName,['key'=>'menu_'.$id],['id'=>$id]);
    }
  }

  public function afterDelete($item){
    $children = $this->db->select($this->tableName,'*',['parent_id'=>$item['id']]);
    if(count($children)){
      $this->db->delete('admin_permissions',['parent_id'=>array_column($children,'key')]);
      $this->db->delete($this->tableName,['parent_id'=>$item['id']]);
    }
    $this->db->delete('admin_permissions',['parent_id'=>$item['key']]);
  }
}